<template>
  <div class="app-container">
    <!-- 搜索表单：调整label-width避免标签换行 -->
    <el-form :model="routeProductQueryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="产品物料编码" prop="itemCode">
        <el-input
          v-model="routeProductQueryParams.itemCode"
          placeholder="请输入产品物料编码"
          clearable
          @keyup.enter="handleRouteProductQuery"
        />
      </el-form-item>
      <el-form-item label="产品物料名称" prop="itemName">
        <el-input
          v-model="routeProductQueryParams.itemName"
          placeholder="请输入产品物料名称"
          clearable
          @keyup.enter="handleRouteProductQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleRouteProductQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetRouteProductQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮：增大间距，提升布局美观度 -->
    <el-row :gutter="16" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleRouteProductAdd"
          v-hasPermi="['routeproduct:routeproduct:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleRouteProductUpdate"
          v-hasPermi="['routeproduct:routeproduct:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleRouteProductDelete"
          v-hasPermi="['routeproduct:routeproduct:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleRouteProductExport"
          v-hasPermi="['routeproduct:routeproduct:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getRouteProductList"></right-toolbar>
    </el-row>

    <!-- 表格：列宽适配长文本，避免挤压 -->
    <el-table v-loading="loading" :data="routeProductList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="recordId" />
      <el-table-column label="产品物料编码" align="center" prop="itemCode" />
      <el-table-column label="产品物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" min-width="120" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="生产数量" align="center" prop="quantity" />
      <el-table-column label="生产用时" align="center" prop="productionTime" />
      <el-table-column label="时间单位" align="center" prop="timeUnitType" />
      <el-table-column label="备注" align="center" prop="remark" min-width="150" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleRouteProductUpdate(scope.row)" v-hasPermi="['routeproduct:routeproduct:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleRouteProductDelete(scope.row)" v-hasPermi="['routeproduct:routeproduct:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件：绑定隔离后的查询参数 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="routeProductQueryParams.pageDto.current"
      v-model:limit="routeProductQueryParams.pageDto.size"
      @pagination="getRouteProductList"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="routeproductRef" :model="routeProductForm" :rules="routeProductRules" label-width="130px">
               <el-col :span="24">
            <el-row gutter="15">
              <el-col :span="8">
                <el-form-item label="产品物料编码" prop="itemCode">
                  <el-input v-model="routeProductForm.itemCode" type="text" placeholder="请输入产品物料编码" clearable
                    :style="{width: '100%'}"></el-input>
  
                </el-form-item>
              </el-col>
              <el-button type="primary" :icon="Search" @click="openProductDialog"></el-button>
              <el-col :span="8">
                <el-form-item label="产品物料名称" prop="itemName">
                  <el-input v-model="routeProductForm.itemName" type="text" placeholder="请选择产品" readonly clearable
                    :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="单位" prop="unitOfMeasure">
                  <el-input v-model="routeProductForm.unitOfMeasure" type="text" placeholder="请选择产品" readonly
                    clearable :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row gutter="15">
              <el-col :span="24">
                <el-form-item label="规格型号" prop="specification">
                  <el-input v-model="routeProductForm.specification" type="textarea" placeholder="请选择产品" readonly
                    :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row gutter="15">
              <el-col :span="12">
                <el-form-item label="生产数量" prop="quantity">
                  <el-input-number v-model="routeProductForm.quantity" placeholder="生产数量"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="23">
            <el-row gutter="15">
              <el-col :span="12">
                <el-form-item label="生产用时" prop="productionTime">
                  <el-input v-model="routeProductForm.productionTime" type="text" placeholder="请输入生产用时" clearable
                    :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label-width="123px" label="选择时间单位" prop="timeUnitType">
                  <el-select v-model="routeProductForm.timeUnitType" placeholder="请选择选择时间单位" clearable
                    :style="{width: '100%'}">
                    <el-option v-for="(item, index) in timeType" :key="index" :label="item.label"
                      :value="item.value" :disabled="item.disabled"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
         <el-col :span="24">
            <el-row gutter="15">
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="routeProductForm.remark" type="textarea" placeholder="请输入备注"
                    :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitRouteProductForm">确 定</el-button>
          <el-button @click="cancelRouteProduct">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <!-- 物料选择弹窗 -->
<el-dialog
  title="选择物料"
  v-model="productDialogVisible"
  width="80%"
  append-to-body
>
  <el-container>
    <!-- 左侧分类树 -->
    <el-aside width="200px" style="background-color: white;">
      <el-table
        style="border: none;"
        v-if="refreshTable"
        :data="type1List"
        row-key="itemTypeId"
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        @row-click="handleCategoryClick"
      >
        <el-table-column align="center" prop="itemTypeName" />
      </el-table>
    </el-aside>

    <!-- 右侧物料列表 -->
    <el-main>
      <!-- 搜索条件 -->
    <el-form 
  :model="queryParams" 
  ref="queryRef" 
  :inline="true" 
  v-show="showSearch" 
  label-width="68px"
>
<el-form-item label="物料编码" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入产品物料编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入产品物料名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
  <el-form-item>
    <el-button 
      type="primary" 
      :icon="Search" 
      @click="handleQuery"
    >搜索</el-button>
    <el-button 
      icon="Refresh" 
      @click="resetQuery"
    >重置</el-button>
  </el-form-item>
</el-form>


      <!-- 物料表格 -->
        <el-table 
          v-loading="materialLoading" 
          :data="itemList" 
          @selection-change="handleMaterialSelection"  
          ref="materialTable"
          border stripe
        >
        <el-table-column type="selection" width="55" align="center" />  <!-- 新增：单选选择列 -->
        <el-table-column label="物料编码" align="center" prop="itemCode" />
        <el-table-column label="物料名称" align="center" prop="itemName" />
        <el-table-column label="规格型号" align="center" prop="specification" />
        <el-table-column label="单位" align="center" prop="unitOfMeasure" />
        <el-table-column label="所属分类" align="center" prop="itemTypeName" />
      </el-table>
      <pagination
        v-show="total2 > 0"
        :total="total2"
        v-model:page="queryParams.pageDto.current" 
        v-model:limit="queryParams.pageDto.size"
        @pagination="getList"
      />
    </el-main>
  </el-container>

  <!-- 底部按钮 -->
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="productDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="confirmSelectItem">确 定</el-button>
    </div>
  </template>
</el-dialog>

</template>

<script setup name="RouteProduct">
import { listRouteproduct, getRouteproduct, delRouteproduct, addRouteproduct, updateRouteproduct } from "@/api/routeproduct/routeproduct";
import { getCurrentInstance, reactive, ref, toRefs,defineProps } from 'vue';
import Pagination from '@/components/Pagination';
import RightToolbar from '@/components/RightToolbar';
import {  Search } from '@element-plus/icons-vue'
import {listItem} from '@/api/item/item'
// import { listItem, getItem, delItem, addItem, updateItem } from "@/api/item/item"
const { proxy } = getCurrentInstance();

// ========== 数据定义（命名空间隔离，避免与主模块冲突） ==========
const routeProductList = ref([]); // 产品列表数据
const open = ref(false);          // 对话框显隐
const loading = ref(true);        // 加载状态
const showSearch = ref(true);     // 搜索栏显隐
const ids = ref([]);              // 选中项ID集合
const single = ref(true);         // 是否单条选中
const multiple = ref(true);       // 是否多条选中
const total = ref(0);             // 总条数
const title = ref("");            // 对话框标题
//下拉表
import { listType1} from "@/api/type1/type1"
const refreshTable = ref(true); // 控制树刷新
const isExpandAll = ref(true);  // 是否默认展开
// 原代码：const selectedItem = ref(null);
const selectedItems = ref([]); // 改为数组，存储勾选的物料（长度最多1）
const materialLoading = ref(false); // 新增：区分物料加载状态
// 固定时间单位下拉选项
const timeType = [
  { label: '分钟', value: 'MIN' },
  { label: '小时', value: 'HOUR' },
  { label: '天', value: 'DAY' }
]

// 响应式核心数据：所有字段添加RouteProduct前缀
const data = reactive({
  routeProductForm: {
     remark: null, // 显式定义
  }, // 表单数据
  routeProductQueryParams: { // 查询参数
    pageDto: {
      current: 1,
      size: 10,
    },
    itemCode: null,
    itemName: null,
  },
  routeProductRules: { // 表单校验规则
    routeId: [
      { required: true, message: "工艺路线ID不能为空", trigger: "blur" }
    ],
    itemCode: [
      { required: true, message: "产品物料编码不能为空", trigger: "blur" }
    ],
    itemName: [
      { required: true, message: "产品物料名称不能为空", trigger: "blur" }
    ],
    quantity: [
      { required: true, message: "生产数量不能为空", trigger: "blur" }
    ],
  }
});
// 关键：定义 props 接收主组件传递的 routeId
const props = defineProps({
  currentRouteId: {
    type: [Number, String], // 支持数字/字符串类型的ID
    default: null, // 默认值为 null（新增工艺路线时无ID）
    required: false
  }
});

const { routeProductQueryParams, routeProductForm, routeProductRules } = toRefs(data);



// ========== 核心函数（命名空间隔离） ==========
/** 查询产品制程列表（修改后） */
function getRouteProductList() {
  loading.value = true;
  // 1. 拼接含routeId的查询参数（关联当前工艺路线）
  const queryParams = {
    ...routeProductQueryParams.value,
    routeId: props.currentRouteId // 关键：携带工艺路线ID
  };
  // 2. 调用接口时传递拼接后的queryParams，而非原routeProductQueryParams.value
  listRouteproduct(queryParams).then(response => {
    routeProductList.value = response.data.records;
    total.value = response.data.pageDto.total;
    loading.value = false;
  }).catch(err => {
    console.error("查询产品制程失败：", err);
    proxy.$modal.msgError("加载失败，请重试");
    loading.value = false;
  });
}

/** 取消对话框 */
function cancelRouteProduct() {
  open.value = false;
  resetRouteProductForm();
}

/** 重置表单 */
function resetRouteProductForm() {
  routeProductForm.value = {
    recordId: null,
     // 关键：赋值父组件传递的 currentRouteId，关联当前工艺路线
    routeId: props.currentRouteId || null, 
    itemId: null,
    itemCode: null,
    itemName: null,
    specification: null,
    unitOfMeasure: null,
    quantity: null,
    productionTime: null,
    timeUnitType: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("routeproductRef");
}

/** 搜索按钮操作 */
function handleRouteProductQuery() {
  routeProductQueryParams.value.pageDto.current = 1;
  getRouteProductList();
}

/** 重置搜索表单 */
function resetRouteProductQuery() {
  proxy.resetForm("queryRef");
  handleRouteProductQuery();
}

/** 多选框选中事件 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleRouteProductAdd() {
  resetRouteProductForm();
  open.value = true;
  title.value = "添加产品制程";
}

/** 修改按钮操作 */
function handleRouteProductUpdate(row) {
  resetRouteProductForm();
  const _recordId = row.recordId || ids.value;
  getRouteproduct(_recordId).then(response => {
    routeProductForm.value = response.data;
    open.value = true;
    title.value = "修改产品制程";
  });
}

function submitRouteProductForm() {
  proxy.$refs["routeproductRef"].validate(valid => {
    if (valid) {
      // ✅ 关键：确保 routeId 补上
      routeProductForm.value.routeId = props.currentRouteId;
         console.log("提交前的表单数据：", routeProductForm.value);
      if (!routeProductForm.value.routeId) {
        proxy.$modal.msgError("请先保存工艺路线，再新增关联产品！");
        return;
      }

      if (routeProductForm.value.recordId != null) {
        // 修改
        updateRouteproduct(routeProductForm.value).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getRouteProductList();
        });
      } else {
        // 新增
        addRouteproduct(routeProductForm.value).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getRouteProductList();
        });
      }
    }
  });
}


/** 删除按钮操作 */
function handleRouteProductDelete(row) {
  const _recordIds = row.recordId || ids.value;
  proxy.$modal.confirm('是否确认删除产品制程编号为"' + _recordIds + '"的数据项？').then(() => {
    return delRouteproduct(_recordIds);
  }).then(() => {
    getRouteProductList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleRouteProductExport() {
  proxy.download('routeproduct/routeproduct/export', {
    ...routeProductQueryParams.value
  }, `routeproduct_${new Date().getTime()}.xlsx`);
}
// 弹窗控制
const productDialogVisible = ref(false);
// const selectedItem = ref(null); // 临时存放用户选中的物料
const queryParams = reactive({
  pageDto: {
    current: 1,
    size: 10
  },
  itemCode: null,
  itemName: null,
  itemTypeId: 1
})
const itemList = ref([]); // 右侧物料列表
const total2 = ref(0); // 分页总条数
const type1List = ref([])//左侧分类树
const data1 = reactive({
  queryParams1: {
  },
})

const { queryParams1 } = toRefs(data1)

// 打开弹窗
function openProductDialog() {
  productDialogVisible.value = true;
  getList(); // 打开时加载物料
}
function getList() {
  loading.value = true;
  listItem(queryParams).then(response => {
    console.log('物料接口返回：', response)
    // 这里根据后端返回结构取值
    itemList.value = response.rows || [];
    total2.value = response.total || 0;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}


// 新增：处理物料勾选事件（核心单选逻辑）
function handleMaterialSelection(selection) {
  if (selection.length > 1) {
    // 超过1个时，只保留最后一个勾选
    const lastItem = selection[selection.length - 1];
    selectedItems.value = [lastItem];
    // 同步表格UI勾选状态
    const tableRef = proxy.$refs.materialTable;
    if (tableRef) {
      tableRef.clearSelection(); // 清空所有勾选
      tableRef.toggleRowSelection(lastItem, true); // 只勾选最后一个
    }
  } else {
    selectedItems.value = selection; // 未超过1个，直接赋值
  }
}

// 原代码：使用selectedItem.value
function confirmSelectItem() {
  if (selectedItems.value.length === 0) { // 改为判断数组长度
    proxy.$modal.msgWarning("请勾选一个物料");
    return;
  }
  const selectedItem = selectedItems.value[0]; // 单选，取第一个元素
  // 回填数据（不变）
  routeProductForm.value.itemId = selectedItem.itemId; 
  routeProductForm.value.itemCode = selectedItem.itemCode;
  routeProductForm.value.itemName = selectedItem.itemName;
  routeProductForm.value.specification = selectedItem.specification
  routeProductForm.value.unitOfMeasure= selectedItem.unitOfMeasure
  routeProductForm.value.itemTypeName = selectedItem.itemTypeName
  productDialogVisible.value = false;
  selectedItems.value = []; // 清空勾选状态
}

function handleQuery() {
  queryParams.pageDto.current = 1; 
  getList()
}
/** 新增：处理物料分类点击事件 */
function handleCategoryClick(row) {
  // 设置选中的分类ID到查询参数
  queryParams.itemTypeId = row.itemTypeId
  // 重置页码为1
   queryParams.pageDto.current = 1; 
  // queryParams.pageNum = 1
  // 执行查询
  getList()
}
/** 查询物料分类列表 */
function getList1() {
  loading.value = true
  listType1(queryParams1.value).then(response => {
    type1List.value = proxy.handleTree(response.data, "itemTypeId", "parentTypeId")
    loading.value = false
  })
}


// 初始化加载列表
getRouteProductList();
getList1()
import { watch, onMounted } from 'vue';
// 新增：标记组件是否挂载完成
const isMounted = ref(false);

// 组件挂载完成后标记
onMounted(() => {
  isMounted.value = true;
});

// 优化watch：仅当组件挂载完成且currentRouteId有值时才加载
watch(
  () => props.currentRouteId,
  (newVal) => {
    if (isMounted.value && newVal) { // 新增isMounted判断
      getRouteProductList();
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>